#!/usr/bin/env ts-node

/**
 * SmartInput 数据管理脚本
 * 提供数据备份、恢复、清理等功能
 */

import fs from 'fs';
import path from 'path';

// 类型定义
interface DeviceInfo {
  id: string;
  type: string;
  name: string;
  capabilities: Record<string, any>;
  isOnline: boolean;
  lastSeen: number;
  timestamp: number;
}

interface PairingRelationship {
  id: string;
  device1Id: string;
  device2Id: string;
  device1Name: string;
  device2Name: string;
  device1Type: string;
  device2Type: string;
  createdAt: number;
  lastActivity: number;
  isActive: boolean;
}

interface PairingCode {
  code: string;
  deviceId: string;
  expiresAt: number;
  isUsed: boolean;
}

interface DataStore {
  devices: Record<string, DeviceInfo>;
  pairings: Record<string, PairingRelationship>;
  pairingCodes: Record<string, PairingCode>;
  stats: {
    lastSave: number;
    totalDevices: number;
    totalPairings: number;
  };
}

// 颜色定义
const colors = {
  red: '\x1b[31m',
  green: '\x1b[32m',
  yellow: '\x1b[33m',
  blue: '\x1b[34m',
  reset: '\x1b[0m'
};

function log(color: keyof typeof colors, message: string): void {
  console.log(`${colors[color]}${message}${colors.reset}`);
}

// 数据文件路径
const dataDir = path.join(process.cwd(), 'data');
const dataFile = path.join(dataDir, 'smartinput-data.json');

/**
 * 备份数据
 */
function backupData(): void {
  try {
    if (!fs.existsSync(dataFile)) {
      log('red', '❌ 数据文件不存在，无法备份');
      return;
    }

    const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
    const backupFile = path.join(dataDir, `backup-${timestamp}.json`);
    
    fs.copyFileSync(dataFile, backupFile);
    log('green', `✅ 数据备份成功: ${backupFile}`);
  } catch (error) {
    log('red', `❌ 数据备份失败: ${error instanceof Error ? error.message : 'Unknown error'}`);
  }
}

/**
 * 恢复数据
 */
function restoreData(backupFile: string): void {
  try {
    if (!fs.existsSync(backupFile)) {
      log('red', '❌ 备份文件不存在');
      return;
    }

    // 验证备份文件
    const data: DataStore = JSON.parse(fs.readFileSync(backupFile, 'utf8'));
    if (!data.devices || !data.pairings || !data.pairingCodes) {
      log('red', '❌ 备份文件格式无效');
      return;
    }

    // 恢复数据
    fs.copyFileSync(backupFile, dataFile);
    log('green', '✅ 数据恢复成功');
  } catch (error) {
    log('red', `❌ 数据恢复失败: ${error instanceof Error ? error.message : 'Unknown error'}`);
  }
}

/**
 * 清理过期数据
 */
function cleanupData(): void {
  try {
    if (!fs.existsSync(dataFile)) {
      log('yellow', '⚠️ 数据文件不存在，无需清理');
      return;
    }

    const data: DataStore = JSON.parse(fs.readFileSync(dataFile, 'utf8'));
    const now = Date.now();
    let cleanedCount = 0;

    // 清理过期的配对码
    for (const [code, pairingCode] of Object.entries(data.pairingCodes || {})) {
      if (now > pairingCode.expiresAt) {
        delete data.pairingCodes[code];
        cleanedCount++;
      }
    }

    // 清理离线设备（超过24小时）
    const deviceTimeout = 24 * 60 * 60 * 1000; // 24小时
    for (const [deviceId, device] of Object.entries(data.devices || {})) {
      if (!device.isOnline && (now - device.lastSeen) > deviceTimeout) {
        delete data.devices[deviceId];
        cleanedCount++;
      }
    }

    if (cleanedCount > 0) {
      fs.writeFileSync(dataFile, JSON.stringify(data, null, 2));
      log('green', `✅ 清理了 ${cleanedCount} 条过期数据`);
    } else {
      log('yellow', 'ℹ️ 没有需要清理的数据');
    }
  } catch (error) {
    log('red', `❌ 数据清理失败: ${error instanceof Error ? error.message : 'Unknown error'}`);
  }
}

/**
 * 查看数据统计
 */
function showStats(): void {
  try {
    if (!fs.existsSync(dataFile)) {
      log('yellow', '⚠️ 数据文件不存在');
      return;
    }

    const data: DataStore = JSON.parse(fs.readFileSync(dataFile, 'utf8'));
    
    log('blue', '📊 数据统计:');
    log('blue', `   设备总数: ${Object.keys(data.devices || {}).length}`);
    log('blue', `   配对关系: ${Object.keys(data.pairings || {}).length}`);
    log('blue', `   配对码: ${Object.keys(data.pairingCodes || {}).length}`);
    
    if (data.stats) {
      log('blue', `   最后保存: ${new Date(data.stats.lastSave).toLocaleString()}`);
    }
  } catch (error) {
    log('red', `❌ 获取统计信息失败: ${error instanceof Error ? error.message : 'Unknown error'}`);
  }
}

/**
 * 列出备份文件
 */
function listBackups(): void {
  try {
    if (!fs.existsSync(dataDir)) {
      log('yellow', '⚠️ 数据目录不存在');
      return;
    }

    const files = fs.readdirSync(dataDir);
    const backups = files.filter(file => file.startsWith('backup-') && file.endsWith('.json'));
    
    if (backups.length === 0) {
      log('yellow', 'ℹ️ 没有找到备份文件');
      return;
    }

    log('blue', '📁 备份文件列表:');
    backups.forEach(backup => {
      const filePath = path.join(dataDir, backup);
      const stats = fs.statSync(filePath);
      log('blue', `   ${backup} (${new Date(stats.mtime).toLocaleString()})`);
    });
  } catch (error) {
    log('red', `❌ 列出备份文件失败: ${error instanceof Error ? error.message : 'Unknown error'}`);
  }
}

/**
 * 显示帮助信息
 */
function showHelp(): void {
  log('blue', '🛠️  SmartInput 数据管理工具');
  log('blue', '==============================');
  log('blue', '');
  log('blue', '使用方法:');
  log('blue', '  npx ts-node data-manager.ts <命令> [参数]');
  log('blue', '');
  log('blue', '命令:');
  log('blue', '  backup          - 备份当前数据');
  log('blue', '  restore <文件>   - 从备份文件恢复数据');
  log('blue', '  cleanup         - 清理过期数据');
  log('blue', '  stats           - 显示数据统计');
  log('blue', '  list            - 列出所有备份文件');
  log('blue', '  help            - 显示此帮助信息');
  log('blue', '');
  log('blue', '示例:');
  log('blue', '  npx ts-node data-manager.ts backup');
  log('blue', '  npx ts-node data-manager.ts restore backup-2024-01-01T12-00-00-000Z.json');
  log('blue', '  npx ts-node data-manager.ts cleanup');
}

/**
 * 主函数
 */
function main(): void {
  const command = process.argv[2];
  const arg = process.argv[3];

  switch (command) {
    case 'backup':
      backupData();
      break;
    case 'restore':
      if (!arg) {
        log('red', '❌ 请指定备份文件路径');
        return;
      }
      restoreData(path.join(dataDir, arg));
      break;
    case 'cleanup':
      cleanupData();
      break;
    case 'stats':
      showStats();
      break;
    case 'list':
      listBackups();
      break;
    case 'help':
    case '--help':
    case '-h':
      showHelp();
      break;
    default:
      log('red', '❌ 未知命令');
      showHelp();
      break;
  }
}

// 运行主函数
if (require.main === module) {
  main();
}

export {
  backupData,
  restoreData,
  cleanupData,
  showStats,
  listBackups,
  DataStore,
  DeviceInfo,
  PairingRelationship,
  PairingCode
}; 